package com.jarvis.hospital;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.hospital.adapter.OperationAdapter;
import com.jarvis.hospital.common.BaseActivity;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.model.LoginModel;
import com.jarvis.hospital.model.OpertionListModel;
import com.jarvis.hospital.model.OpertionModel;
import com.jarvis.hospital.model.UserInfoModel;
import com.jarvis.hospital.servers.WebService;
import com.jarvis.hospital.util.DividerItemDecoration;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class OperationListActivity extends BaseActivity {
    @BindView(R.id.recy_operation)
    RecyclerView recy_operation;
    @BindView(R.id.ptr_opertion)
    PtrClassicFrameLayout ptr_opertion;
    private OperationAdapter operationAdapter;

    private WebService webService;
    private int pageSize = 10;
    private int currentPage = 1;
    private int maxPage = 1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_orperation_list;
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        ptr_opertion.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        ptr_opertion.autoRefresh();
                    }
                }, 100);
    }

    @Override
    public void initView() {
        webService = RequestApi.create(WebService.class);
        setAdapter();
        setRefresh();
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.activity_empty, null);
        operationAdapter.setEmptyView(true,view);
        recy_operation.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                OpertionModel opertionModel = operationAdapter.getData().get(i);
                String taskTimeAct = opertionModel.getTaskTimeAct();
                if ("0".equals(taskTimeAct)){
                    Bundle bundle = new Bundle();
                    bundle.putString("taskId", opertionModel.getTaskId());
                    bundle.putString("status", "0");
                    startActivity(OperationDetailActivity.class, bundle);
                }else if ("-1".equals(taskTimeAct)){
                    Bundle bundle = new Bundle();
                    bundle.putString("taskId", opertionModel.getTaskId());
                    bundle.putString("status", "1");
                    startActivity(OperationDetailActivity.class, bundle);
                }else {
                    showTextToast("当前任务已处理");
                }
            }
        });
    }

    /**
     * 设置adapter
     */
    public void setAdapter() {
        operationAdapter = new OperationAdapter(R.layout.item_operation, new ArrayList<OpertionModel>());
        recy_operation.setLayoutManager(new LinearLayoutManager(this));
        //recy_operation.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        operationAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_operation.setAdapter(operationAdapter);
    }

    /**
     * 设置下拉刷新
     */
    public void setRefresh() {
        ptr_opertion.setMode(PtrFrameLayout.Mode.BOTH);
        ptr_opertion.disableWhenHorizontalMove(true);
        ptr_opertion.setLastUpdateTimeRelateObject(this);
        ptr_opertion.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_operation, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_operation, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                if (currentPage < maxPage) {
                    currentPage++;
                    loadData();
                } else {
                    ptr_opertion.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                operationAdapter.setNewData(new ArrayList<OpertionModel>());
                currentPage = 1;
                loadData();
            }
        });
    }

    private void loadData() {
        UserInfoModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userId = userModel.getUserId();
        webService.getTaskListOnWatch(currentPage, pageSize, userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<OpertionListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<OpertionListModel> opertionListModelResponseData) {
                        if (opertionListModelResponseData != null) {
                            int resultCode = opertionListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                int total_count = opertionListModelResponseData.getTotalcount();
                                maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                                operationAdapter.addData(opertionListModelResponseData.getData().getTaskList());
                            } else {
                                showTextToast(opertionListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ptr_opertion.refreshComplete();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        ptr_opertion.refreshComplete();
                    }
                });
    }
}
